package com.example.socket.filter.heart;

import com.example.socket.core.Command;
import com.example.socket.core.Message;
import com.example.socket.core.Session;
import com.example.socket.handler.AbstractListener;
import com.example.socket.server.ServerDispatcher;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;

public class HeartReceiverFilter extends AbstractListener {

    /**心跳包对应方法*/
    private Command command;
    @Autowired
    private ServerDispatcher serverDispatcher;
    /**是否回复*/
    private boolean response = true;

    public void setResponse(boolean response) {
        this.response = response;
    }

    @PostConstruct
    void init() {
        serverDispatcher.addListener(this);
    }

    public HeartReceiverFilter(short command, short module) {
        this.command = Command.valueOf(module, command);
    }

    @Override
    public void received(Message message, Session session) {
        if (command.equals(message.getCommand())) {
            if (logger.isDebugEnabled()) {
                logger.debug("服务端收到从[{}]发来的心跳包", session.getRemoteAddress());
            }
            if (response) {
                dispatcher.send(message, session);
            }
            message.setIgnore(true);
        }
    }
}